<?php

namespace Lettral\Latex;

use Lettral\Helpers\ResponseCreator;

use Symfony\Tests\Component\Translation\String;

use Lettral\LetterBundle\Entity\Lettre;

class LatexGenerator
{
	/**
	 * Fichier de commande
	 * @var unknown_type
	 */
	private $commandFile;

	/**
	 * Chemin du dossier temporaire où sera réalisé la conversion
	 * @var unknown_type
	 */
	private $dirName;
	
	/**
	 * Lettre à générer
	 * @var Lettral\LetterBundle\Entity\Lettre()
	 */
	private $letter;
	
	/**
	 * Date de génération
	 * @var \DateTime()::
	 */
	private $date;
	
	/**
	 * Chemin absolu du dossier web
	 * @var unknown_type
	 */
	private static $absolutePath = "C:/Wamp/www/Symfony/web/";
	
	/**
	 * Dossier où sont stockés les pdf terminés
	 * @var unknown_type
	 */
	private static $completeDirName = "letters/complete/";
	
	/**
	 * Dossier où sont stockés les fichiers temporaires pour la génération 
	 * @var unknown_type
	 */
	private static $tempDirName = "letters/temp/";
	
	/**
	 * Crée le fichier de commande pour une lettre
	 * @param Lettre $letter
	 * @return boolean
	 */
	public function generateCommands(Lettre $letter) {

		$this->init($letter);		
								
		$this->writeDate();
		$this->writeCommand('tLieu', $this->letter->getLieuEcriture());
		$this->writeCommand('tVref', $this->letter->getVref());
		$this->writeCommand('tNref', $this->letter->getNref());
		$this->writeCommand('tObjet', $this->letter->getSujet());
		$this->writeCommand('tOuverture', $this->letter->getOuv());
		$this->writeContent();
		$this->writeCommand('tFermeture', $this->letter->getFerm());
		$this->writeDestCommand();
		$this->writeExpCommand();
		$this->writeCommand('tSignature', $this->letter->getSign());
		$this->writePj();
		
		fclose($this->commandFile);
		
		return true;
	}
	
	/**
	 * Génère un pdf de la lettre courante
	 */
	public function generatePdf() {
 		$command = "cd " . LatexGenerator::$absolutePath . $this->dirName ." & pdflatex -interaction=nonstopmode -quiet lettre.tex";
		$command .= " & pdflatex -interaction=nonstopmode -quiet lettre.tex"; 
				
		$output;
		exec($command, $output, $return_var);
		if ($output == null) {
			$this->finishGeneration();	
			return true;
		}		
		return false;
	}
	
	/**
	 * Vérifie s'il existe un pdf pour la lettre
	 * @param Lettre $letter
	 * @return chemin de la lettre
	 */
	public static function checkGeneratedLetter(Lettre $letter) {
		$filename = LatexGenerator::$completeDirName . "/lettre" . $letter->getNumLettre() . ".pdf";
		return file_exists($filename) ? $filename : null;
	}
	
	/**
	 * Etape d'initialisation avant la génération
	 * @param Lettre $letter
	 */
	private function init(Lettre $letter) {
		$this->letter = $letter;
		if ($letter->getUser()->getId() == null)
			throw \Exception;
		$letter->setDateGeneration(new \DateTime("now"));
		$this->date = $letter->getDateGeneration();
		$this->dirName = LatexGenerator::$tempDirName . $letter->getNumLettre(). "_" . $letter->getUser()->getId(). "_" .$this->date->format('Ymd_His');
		mkdir($this->dirName);
		copy("letters/models/model1.tex", $this->dirName . "/lettre.tex");
		$this->commandFile = fopen($this->dirName . '/commands.tex', 'w+');
		fputs(fopen($this->dirName . '/.htaccess', 'w+'), 'deny from all');
	}
	
	/**
	 * Ecrit une commande Latex dans le fichier de commande
	 * @param string $commandName
	 * @param string $content
	 */
	private function writeCommand($commandName, $content) {		
		fputs($this->commandFile, "\\newcommand{\\" . $commandName . "}{" . $content . "}\n");
	}
	
	private function writeContent() {
		$content = $this->letter->getContenu();		
		$this->writeCommand('tContenu', $this->cleanContent($content));
	}
	
	/**
	 * Ecrit la commande pour les coordonnées du destinataire
	 */
	private function writeDestCommand() {
		$content = $this->letter->getNomDest();
		if ($this->letter->getCompNomDest1() != null) $content .= "\\\\" . $this->letter->getCompNomDest1();
		if ($this->letter->getCompNomDest2() != null) $content .= "\\\\" . $this->letter->getCompNomDest2();
		if ($this->letter->getAdresseDest() != null) $content .= "\\\\" . $this->letter->getAdresseDest();
		if ($this->letter->getCpDest() != null) $content .= "\\\\" . $this->letter->getCpDest();
		if ($this->letter->getVilleDest() != null) $content .= " " . $this->letter->getVilleDest();
		fputs($this->commandFile, "\\newcommand{\\tDest}{" . $content . "}\n");
	}

	/**
	 * Ecrit la commande pour les coordonnées de l'expéditeur
	 */
	private function writeExpCommand() {
		$nom = $this->letter->getUser()->getPrenom()." ".strtoupper($this->letter->getUser()->getNom());
		$this->writeCommand('tNomExp', $nom);
		$content = $nom . "\\\\" . $this->letter->getUser()->getAdresse();
		$content .= "\\\\" . $this->letter->getUser()->getCp() . " " . $this->letter->getUser()->getVille();
		$this->writeCommand('tExp', $content);
		$this->writeCommand('tTMobile', $this->letter->getUser()->getPort());
		$this->writeCommand('tTFixe', $this->letter->getUser()->getFixe());
		$this->writeCommand('tEmail', $this->letter->getUser()->getDisplayEmail());
	}
	
	private function writePj() {
		$pj = "";
		if ($this->letter->getPj1() != null) $pj .= $this->letter->getPj1();
		if ($this->letter->getPj2() != null) $pj .= "\\\\" . $this->letter->getPj2();
		if ($this->letter->getPj3() != null) $pj .= "\\\\" . $this->letter->getPj3();
		$this->writeCommand('tPj', $pj);		
	}
	
	/**
	 * Ecrit la commande de date
	 */
	private function writeDate() {
		$date = $this->letter->getDateEcriture();
		if ($date == null) {
			$this->writeCommand('tDate','\\today');
		}
		else {
			$dateStr = "";
			
			$day = intval($date->format('d'));
			if ($day == "1") {
				$dateStr = "1\up{er}";
			} else {
				$dateStr = $day;
			}
			
			$month = intval($date->format('m'));
			switch ($month) {
				case 1 :
					$dateStr .= " janvier";
					break;
				case 2 :
					$dateStr .= " février";
					break;
				case 3 :
					$dateStr .= " mars";
					break;
				case 4 :
					$dateStr .= " avril";
					break;
				case 5 :
					$dateStr .= " mai";
					break;
				case 6 :
					$dateStr .= " juin";
					break;
				case 7 :
					$dateStr .= " juillet";
					break;
				case 8 :
					$dateStr .= " août";
					break;
				case 9 :
					$dateStr .= " septembre";
					break;
				case 10 :
					$dateStr .= " octobre";
					break;
				case 11 :
					$dateStr .= " novembre";
					break;
				case 12 :
					$dateStr .= " décembre";
					break;
				default:
					$dateStr .= " erreur";
					break;
			}

			$dateStr .= " ".$date->format('Y');
			$this->writeCommand('tDate', $dateStr);
		}
	}
	
	/**
	 * Fonction supplémentaire pour nettoyer le code Latex
	 * @param unknown_type $content
	 * @return unknown
	 */
	private function cleanContent($content) {

// 		if (substr($content, 0, 2) == "\\\\") {		
// 			return substr($content, 2);
// 		}
		return $content;
	}
	
	/**
	 * Quand la génération a réussi, nettoie les fichiers temp et stocke la lettre
	 */
	private function finishGeneration() {
		// copie du pdf dans le dossier adéquat
		copy(LatexGenerator::$absolutePath . $this->dirName . "\\lettre.pdf", LatexGenerator::$completeDirName . "lettre" . $this->letter->getNumLettre() .".pdf");
		
		// suppression des fichiers du dossier temporaire
		$dir = opendir($this->dirName);
		while($file = readdir($dir)) {
			$filePath = $this->dirName . "/" . $file;
			if (is_file($filePath)) unlink($filePath);
		}		
		closedir($dir);
		
		// suppression du dossier
		rmdir(LatexGenerator::$absolutePath . $this->dirName);
	}
	
}